package cn.foodshopping.service.impl;
import cn.foodshopping.domain.User;
import cn.foodshopping.mapper.UserMapper;
import cn.foodshopping.service.IUserService;
import cn.foodshopping.util.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class UserServiceImpl implements IUserService {
@Autowired
    UserMapper userMapper;
    @Override
    public Result login(String code, String avatarUrl, String nickName) {
        String openid=null;
        System.out.println(code+"-----"+avatarUrl+"-------"+nickName);
        //发送网路请求去查询当前用户的Penid
        String url="https://api.weixin.qq.com/sns/jscode2session?appid=wx92d7a8330d7eb3e3" +
                "&secret=b0f2bebe92760e1664e0717a06edbc58" +
                "&js_code="+code+"&grant_type=authorization_code";
        System.out.println(url);
        //发送网络请求GET
        RestTemplate restTemplate=new RestTemplate();
        ResponseEntity<String> forentity=restTemplate.getForEntity(url,String.class);
        System.out.println(forentity.getHeaders());
        System.out.println(forentity.getBody());
        //字符串转化为json
        ObjectMapper jsonNode=new ObjectMapper();
        try{
            JsonNode jsonNode1=jsonNode.readTree(forentity.getBody());
            openid=jsonNode1.get("openid").asText();
            System.out.println(openid);
        }catch (JsonProcessingException e){
            e.printStackTrace();
        }
        if (openid!=null&& !openid.isEmpty()) {
            User user=userMapper.queryByOpenid(openid);
            if (user!=null){
                System.out.println("---登录");
                return  new Result(200,"登录成功",user);
            }else {
                //添加到数据库
                user=new User();
                System.out.println("---注册");
                userMapper.insert(avatarUrl,nickName,openid);
                user.setOpenId(openid);
                user.setImageUrl(avatarUrl);
                user.setNickName(nickName);
                return  new Result(200,"注册成功",user);
            }
        }else {
            System.out.println("---失败");
            return new Result(201,"登录失败",null);
        }
    }
}
